package queuedemo;

public class MyQueue {
    //用双链表实现队列

    //结点类
    static class ListNode {
        public int val;
        public ListNode next;
        public ListNode prev;

        //提供构造方法

        public ListNode(int val) {
            this.val = val;
        }
    }

    public ListNode head;//头结点
    public ListNode last;//尾结点

    /**
     * 1.尾插法
     * 相当于入队
     */
    public void offer(int val) {
        ListNode node = new ListNode(val);
        if (head == null) {
            head = last = node;
        } else {
            last.next = node;
            node.prev = last;
            last = last.next;
        }
    }

    /**
     * 2.头删
     * 相当于出队
     */
    public int poll() {
        if (head == null) {
            return -1;
        }
        int val = -1;
        if (head.next == null) {
            val = head.val;
            head = null;
            last = null;
            return val;
        }
        val = head.val;
        head = head.next;
        head.prev = null;
        return val;
    }

    public boolean empty() {
        return head == null;
    }

    public int peek(){
        if (head == null){
            return -1;
        }
        return head.val;
    }
}
